package com.zzyl.member.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.member.domain.Reservation;
import com.zzyl.member.dto.ReservationCountDTO;
import com.zzyl.member.dto.ReservationDto;
import com.zzyl.member.mapper.ReservationMapper;
import com.zzyl.member.service.IReservationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDate;
import java.util.List;

/**
 * 预约信息Service业务层处理
 *
 * @author CHEN
 * @date 2025-07-31
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {

    @Autowired
    private ReservationMapper reservationMapper;


    /**
     * 查询预约信息列表
     *
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }


    /**
     * 查询当天取消预约数量
     *
     * @return
     */
    @Override
    public Integer getCancelledCount() {
        // 获取当前用户ID
        Long userId = UserThreadLocal.getUserId();
        //通过用户id查询手机号
        //String mobile = this.baseMapper.selectById(userId).getMobile();
        return reservationMapper.getCancelledCount(userId);
    }


    /**
     * 新增预约
     *
     * @param reservationDto
     * @return
     */
    @Override
    public void insertReservation(ReservationDto reservationDto) {
        //查询预约次数
        Integer cancelledCount = getCancelledCount();
        if (cancelledCount >3) {
            throw new BaseException("当天取消预约次数超过3次,请明天再试!");
        }

        /*
         eservation reservation = new Reservation();
         BeanUtils.copyProperties(reservationDto, reservation);
        */
        Reservation reservation = BeanUtil.toBean(reservationDto, Reservation.class);
        //验证手机号,预约时间是否存在
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getMobile, reservation.getMobile())
                .eq(Reservation::getTime, reservation.getTime())
                .eq(Reservation::getStatus, 0);
        if (reservationMapper.selectCount(queryWrapper) > 0) {
            throw new BaseException("该手机号已预约该时间段");
        }

        //设置预约状态
        reservation.setStatus(0);
        //设置创建人
        reservation.setCreateBy(UserThreadLocal.getUserId().toString());
        reservationMapper.insert(reservation);
    }

    /**
     * 查询预约时间段预约数量
     *
     * @param date
     * @return
     */
    // 最大预约次数
    private static final int MAX_COUNT = 6;

    /**
     * 查询预约时间段剩余预约次数
     *
     * @param date
     * @return
     */
    @Override
    public List<ReservationCountDTO> countByTime(LocalDate date) {
        // 查询数据库已用次数
        List<ReservationCountDTO> usedList = reservationMapper.countByTime(date.atStartOfDay(), date.plusDays(1).atStartOfDay());

        // 计算剩余次数
        for (ReservationCountDTO dto : usedList) {
            dto.setCount(Math.max(0, MAX_COUNT - dto.getCount()));
        }

        return usedList;
    }

    /**
     * 修改预约
     *
     * @param id
     * @return
     */
    @Override
    public Boolean updateReservationById(Long id) {
        // 查询预约记录
        Reservation reservation = reservationMapper.selectById(id);
        if (reservation == null) {
            // 不存在
            return false;
        }
        // 已取消直接返回
        if (reservation.getStatus() == 2) {
            // 避免重复取消
            return false;
        }
        // 更新状态为 2（取消），并记录取消时间
        int rows = reservationMapper.updateStatusToCancel(id);
        return rows > 0;
    }

    @Override
    public boolean save(Reservation entity) {
        return super.save(entity);
    }


}
